<template>
    <div class="app-container">
        <template v-if="!userStore.hasLocalEmail">
            <NoEmail />
        </template>
        <template v-else>
            <div class="top-wrapper">
                <div style="flex: 1;">
                    <el-form :model="queryParams" ref="queryForm" :inline="true" @submit.prevent>
                        <el-form-item label="主题" prop="subject">
                            <el-input v-model="queryParams.subject" placeholder="请输入关键字" clearable style="width: 240px;"
                                @keyup.enter="handleQuery" />
                        </el-form-item>
                    </el-form>
                    <el-button-group>
                        <el-button bg text type="primary" @click="handleAdd" icon="edit"
                            v-hasFunc="'msg:email:save'">写邮件</el-button>
                        <el-button bg text type="primary" @click="handleRefresh" icon="refresh">刷新</el-button>
                        <el-button bg text type="danger" @click="handleDelete" icon="delete"
                            v-hasFunc="'msg:email:del'">删除</el-button>
                    </el-button-group>
                </div>
            </div>
            <splitpanes class="email-split">
                <pane min-size="25" size="25" style="padding-right: 20px;" class="email-panel">
                    <div>
                        <el-segmented v-model="queryParams.status" @change="handleStatusChange"
                            :options="options.statusOptions" style="width: 100%;">
                            <template #default="{ item }">
                                <div class="item">
                                    <div>{{ item.label }}</div>
                                </div>
                            </template>
                        </el-segmented>
                    </div>
                    <div style="flex: 1;overflow: auto;">
                        <LeftPane ref="leftPanel" v-loading="loading" v-model="dataList" @mail-change="onMailChange"
                            :beforeChange="beforeMailChange" />
                    </div>
                    <pagination layout="total,prev, pager, next" v-show="total > 0" :total="total"
                        v-model:page="queryParams.pageIndex" v-model:limit="queryParams.pageSize"
                        @pagination="getEmailList" />
                </pane>
                <pane>
                    <RightPane ref="rightPanel" v-model="email" v-loading="editLoading" />
                </pane>
            </splitpanes>
        </template>
    </div>
</template>

<script setup>
import useUserStore from '@/store/modules/user'
import { getEmails, listEmails, delEmails } from "@/api/msg/emails.js";
import LeftPane from './left'
import RightPane from './write'
import NoEmail from "../NoEmail.vue"
const { proxy } = getCurrentInstance()

const userStore = useUserStore();
const editLoading = ref(false);
const loading = ref(false)
const rightPanel = ref();
const leftPanel = ref();
const total = ref(0);
const email = ref()
// 数据集
const dataList = ref([]);
// 查询参数
const queryParams = reactive({
    pageIndex: 1,
    pageSize: 10,
    status: 0,
    subject: undefined,
});


const state = reactive({
    options: {
        statusOptions: [
            { label: "草稿箱", value: 0, icon: "message" },
            { label: "已发邮件", value: 1, icon: "message" }
        ],
    }
})

const { options } = toRefs(state)


// 重置表单
const reset = () => {
    email.value = {
        subject: "未命名",
        body: '',
        audienceId: [],
        status: 0,
    }
};


//邮件选择改变之前触发
const beforeMailChange = async () => {
    if (email.value) await rightPanel.value.autoSaveDraft();
    return true;
}

// 新增按钮操作
const handleAdd = () => {
    let draft = {
        subject: "未命名",
        body: '',
        audienceId: [],
        status: 0,
    }
    let length = dataList.value.unshift(draft);
    total.value = length;
    email.value = draft;
    leftPanel.value.setCurrentRow(draft);
};

//分段器切换
const handleStatusChange = (value) => {
    queryParams.readStatus = value;
    handleQuery();
}


// 搜索按钮操作
const handleQuery = () => {
    queryParams.pageIndex = 1;
    getEmailList();
};

/** 刷新事件 */
const handleRefresh = () => {
    getEmailList();
}

/**删除选中邮件 */
const handleDelete = async () => {
    try {
        const selectedRows = await leftPanel.value.getSelectRows();
        const ids = selectedRows.map(item => item.id);
        if (ids.length === 0) {
            proxy.$modal.msgWarning("请选择需要删除的邮件");
            return;
        }
        await proxy.$modal.confirm('确认删除所选邮件？');
        loading.value = true;
        await delEmails(ids);
        proxy.$modal.msgSuccess("删除成功");
        getEmailList();
    } catch (error) {
        console.error(error);
    } finally {
        loading.value = false;
    }
}

/** 查询邮箱列表 */
function getEmailList() {
    loading.value = true;
    return listEmails(queryParams).then(({ result, totalNum }) => {
        dataList.value = result;
        total.value = totalNum;
        return result;
    }).finally(res => {
        loading.value = false;
    });
};

const onMailChange = (mailId) => {
    editLoading.value = true;
    getEmails(mailId).then((response) => {
        email.value = response
    }).finally(() => {
        editLoading.value = false;
    });
}

if (userStore.hasLocalEmail) { 
    getEmailList();
}

</script>


<style lang="scss">
@import './index.scss';
</style>
